<template>
    <div class="roles">
      <separator :nameList='newNameList'></separator>
      <el-card>
        <el-row>
          <el-col>
            <el-button type="primary" @click="_addRoles">添加角色</el-button>
          </el-col>
          <el-table :data="rolesList" border style="width: 100%" stripe>
            <el-table-column  type="expand" >
              <template slot-scope="scope">
                 <el-row v-for="(item1,i1) in scope.row.children" :key='i1' :class="['el-bottom',i1===0 ? 'el-top' : '','el-flex']">
                   <el-col :span='5' >
                     <el-tag closable @close='del_roles(scope.row,item1.id)'>{{item1.authName}}</el-tag> 
                     <i class="el-icon-caret-right"></i>
                   </el-col>
                   <el-col :span='19'>
                     <el-row  v-for="(item2,i2) in item1.children" :key='i2' :class="[i2===0 ? '' :'el-top','el-flex']">
                       <el-col :span='6' class="el-col-one">
                         <el-tag type="success" closable @close='del_roles(scope.row,item2.id)'>{{item2.authName}}</el-tag>
                         <i class="el-icon-caret-right"></i>
                        </el-col>
                       <el-col :span='18'>
                          <el-tag type="warning" closable @close='del_roles(scope.row,item3.id)' v-for="(item3,i3) in item2.children" :key="i3">{{item3.authName}}</el-tag>
                       </el-col>
                     </el-row>  
                   </el-col>   
                 </el-row>
              </template>
            </el-table-column>  
            <el-table-column  type="index"></el-table-column>
            <el-table-column  prop="roleName" label="角色名称"></el-table-column>
            <el-table-column  prop="roleDesc" label="角色描述"></el-table-column>
            <el-table-column  label="操作" width="300px">
              <template slot-scope="scope">
                 <el-button type="primary" icon="el-icon-edit" size='mini' @click="editorRoles(scope.row.id)">编辑</el-button>
                 <el-button type="danger" icon="el-icon-delete" size='mini' @click="delRoles(scope.row.id)">删除</el-button>
                 <el-button type="warning" icon="el-icon-orange" size='mini' @click="assignPermissionsClick(scope.row)">分配权限</el-button>
              </template>
             </el-table-column>
           </el-table>  
        </el-row>
      </el-card>
      <!--增加角色 会话框 -->
      <el-dialog title="增加权限列表" :visible.sync="addRolesIalog" width="50%">
        <div class="addRoles">
          <el-form ref="addRolesForm" :model="addRolesForm" :rules='addRoles' label-width="80px">
            <el-form-item label="角色名称" prop="rolesName">
              <el-input v-model="addRolesForm.rolesName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="rolesDescribe">
              <el-input v-model="addRolesForm.rolesDescribe"></el-input>
            </el-form-item>
          </el-form>  
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="CancelAdddRoles">取 消</el-button>
          <el-button type="primary" @click="sureAdddRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑权限列表数据会话框 -->
      <el-dialog title="增加权限列表" :visible.sync="editorRolesIalog" width="50%">
        <div class="addRoles">
          <el-form ref="editorRolesForm" :model="editorRolesList" :rules='editorRoles_g' label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="editorRolesList.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="editorRolesList.roleDesc"></el-input>
            </el-form-item>
          </el-form>  
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="CancelEditordRoles">取 消</el-button>
          <el-button type="primary" @click="sureEditorRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限会话框 -->
      <el-dialog title="分配权限" :visible.sync="assignPermissions" width="40%" @close='treeaCancel' >
        <div class="permissionsTree">
          <el-tree :data="permList" 
                   :props="treeProps" 
                   show-checkbox 
                   default-expand-all
                   node-key='id' 
                   :default-checked-keys="defaultList"
                   ref='treePermissionsRef'
                   >
          </el-tree>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="treeaCancel">取 消</el-button>
          <el-button type="primary" @click="treeSureButton">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
  import Separator from 'components/content/separator/Separator'
  import {getRoles,addRoles,getRolesId,saveRoles,delRolesId,delRolesItem,getPermissions,setPermissions} from 'network/power/roles'

  export default {
    name:'Roles',
    components:{
        Separator
    },
    created(){
      this._getRoles()
    },
    data(){
      return{
        newNameList:['权限列表','角色列表'],
        rolesList:[],
        //权限增加会话框
        addRolesIalog:false,
        // 添加用户数据绑定
        addRolesForm:{
          rolesName:'后台总账号',
          rolesDescribe:'干啥都行'
        },
        // 添加权限验证规则
        addRoles:{
           rolesName:[
             {required:true,message:'请输入角色名称',trigger:'blur'},
             {min:3,max:6,trigger:'blur'}
           ],
           rolesDescribe:[
             {required:true,message:'请输入角色描述',trigger:'blur'},
             {min:6,max:30,trigger:'blur'}
           ]
        },
        // 编辑权限会话框
        editorRolesIalog:false,
        //编辑权限会话框验证规则
        editorRoles_g:{
          roleName:[
             {required:true,message:'请输入角色名称',trigger:'blur'},
             {min:3,max:6,trigger:'blur'}
           ],
           roleDesc:[
             {required:true,message:'请输入角色描述',trigger:'blur'},
             {min:6,max:30,trigger:'blur'}
           ]
        },
        //保存编辑用户后台获取数据
         editorRolesList:{},
        //  分配权限对话框
         assignPermissions:false,
         //权限列表返回数据的形式
         typePerm:'tree',
         //保存后台获取的权限数据
         permList:[],
        //tree空间绑定数据的类型
         treeProps:{
           label:'authName',
           children:'children'
         },
        //  保存三级权限id(默认选中的id值)
         defaultList:[],
         //保存最外层权限的id值
         roleId:''
      }
    },
    methods:{
      // 获取权限列表
      _getRoles(){
        getRoles().then(res=>{
          this.rolesList=res.data.data 
        },err=>{
          console.log(err);
        });
      },
      //增加权限
      _addRoles(){
        this.addRolesIalog=true;
      },
      //增加权限会话框确定按钮
      sureAdddRoles(){
       this.$refs.addRolesForm.validate(vali=>{
         if(!vali){
           return false
         }
         addRoles(this.addRolesForm.rolesName,this.addRolesForm.rolesDescribe).then(res=>{
            console.log(res);
            if(res.data.meta.status!==201){
              return this.$message.error('增加失败');
            }
            this.$message.success('增加成功');
            //刷新数据列表
            this._getRoles();
            //关闭会话框
            this.addRolesIalog = false;
          },err=>{
            console.log(err);
          }) 
        })
      },
      //取消关闭增加权限会话框
      CancelAdddRoles(){
        this.$refs.addRolesForm.resetFields();
        //关闭会话框
        this.addRolesIalog = false;
      },
      //编辑用户权限列表
      editorRoles(id){
        this.editorRolesIalog = true;
        getRolesId(id).then(res=>{
          if(res.data.meta.status!==200){
            return this.$message.error('用户数据获取失败');
          }
          this.editorRolesList=res.data.data
          console.log(res)
        },err=>{

        })
      },
      // 编辑用户会话框取消按钮
      CancelEditordRoles(){
        this.$refs.editorRolesForm.resetFields();
        this.editorRolesIalog = false
      },
      // 编辑用户会话框确定按钮
      sureEditorRoles(){
        this.$refs.editorRolesForm.validate(vali=>{
          if(!vali){
            return false;
          }
          console.log(this.editorRolesList);
          saveRoles(this.editorRolesList.roleId,this.editorRolesList.roleName,this.editorRolesList.roleDesc).then(res=>{
            if(res.data.meta.status!==200){
              return this.$message.error('编辑失败');
            }
            this.$message.success('编辑成功');
            //刷新数据列表
            this._getRoles();
            //关闭弹框
            this.editorRolesIalog = false
          },err=>{
              console.log(err);
          })
        })
      },
      // 删除权限列表
      delRoles(id){
        this.$confirm('此操作将永久删除该权限列表, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRolesId(id).then(res=>{
            if(res.data.meta.status!==200){
              return false
            }
            this.$message({type: 'success', message: '删除成功!' });
          //刷新数据列表
          this._getRoles();
          },err=>{
            console.log(err);
          });
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除' });          
        });
      },
      del_roles(roleId,rightId){
         this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRolesItem(roleId.id,rightId).then(res=>{
            this.$message({type: 'success', message: '删除成功!'});
            roleId.children = res.data.data
          },err=>{
            console.log(err);
          })
        }).catch(() => {
          this.$message({ type: 'info', message: '已取消删除'});          
        });
      },
      // 分配权限对话框
      assignPermissionsClick(role){
        getPermissions(this.typePerm).then(res=>{
          if(res.data.meta.status!==200){
            return this.$message.error('数据获取失败');
          }
          this.permList = res.data.data;
          this.getDefaultList(role,this.defaultList);
          this.roleId=role.id;
          this.assignPermissions = true
       },err=>{
          console.log(err);
       })    
      },
      //通过递归的方式 获取角色下所有三级权限id 并保存到defaultList数组中
      getDefaultList(node,arr){
        //如果是三级节点，这个node节点中不包含children属性，并把id 值保存到arr 数组中
        if(!node.children){
          return arr.push(node.id)
        }
        //如果不是三级节点，需要循环递归出三级节点的id
       node.children.forEach(item => {
         this.getDefaultList(item,arr)
       });
      },
      //分配权限tree弹框关闭按钮及分配权限会话框关闭
      treeaCancel(){
        this.defaultList=[];
        this.assignPermissions = false
      },
       //分配权限tree弹框确定按钮
      treeSureButton(){
        const rids=[
          ...this.$refs.treePermissionsRef.getCheckedKeys(),
          ...this.$refs.treePermissionsRef.getHalfCheckedKeys()
        ];
        const ridsList = rids.join(',');
        console.log(rids);
        console.log(ridsList);
        console.log(this.roleId);
        setPermissions(this.roleId,ridsList).then(res=>{
          console.log(res);
          if(res.data.meta.status!==200){
            return this.$message.error('权限分配失败');
          }
          this.$message.success('权限分配成功');
          //刷新权限数据列表
          this._getRoles();
          this.assignPermissions = false
        },err=>{
           console.log(err);
        })
      }
      
    }
  }
</script>

<style lang="less" scoped>
  .el-table{
      margin-top: 50px;
  }
  .el-bottom{
    border-bottom: 1px solid #e2e2e2;
  }
  .el-top{
    border-top:1px solid #e2e2e2 ;
  }
  .el-tag{
    margin: 15px;  
  }
  .el-flex{
    display:flex ;
    align-items: center;
  }
</style>